package com.sdy.dcsb.web.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sdy.common.model.Response;
import jdk.nashorn.internal.objects.NativeArray;
import jdk.nashorn.internal.objects.NativeJava;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

/**
 * 脚本工具类
 * @author Snaky
 * @date 2020/4/20
 */
public class ScriptUtil {

    public static ScriptEngine getDefaultScriptEngine(){
        ScriptEngineManager manager = new ScriptEngineManager();
        return manager.getEngineByName("JavaScript");
    }

    /**
     *
     * @param path 脚本文件路径
     * @param funcName 执行函数名称
     * @return 执行结果
     */
    @SuppressWarnings("unchecked")
    public static Response<JSONArray> invokeFunction(Path path, String funcName, Map<String,String> paramMap){
        try {
            ScriptEngine engine = ScriptUtil.getDefaultScriptEngine();
            Reader scriptReader = Files.newBufferedReader(path);
            engine.eval(scriptReader);
            engine.put("paramMap",paramMap);

            if(engine instanceof Invocable){
                Invocable invoke = (Invocable) engine;
                Object scriptResult = invoke.invokeFunction(funcName);
                if(scriptResult == null){
                    return Response.error("脚本执行结果为空");
                }
                Response scriptResponse = JSONObject.parseObject(String.valueOf(scriptResult),Response.class);
                Object scriptData = scriptResponse.getData();
                if(scriptData != null && !(scriptData instanceof JSONArray)){
                    return Response.error("脚本执行结果格式异常");
                }
                return scriptResponse;
            }
            return Response.error("脚本不可调用");
        } catch (Exception e){
            if(e instanceof NoSuchMethodException){
                return Response.error("脚本中不存在对应函数");
            }
            e.printStackTrace();
            return Response.error(e.getMessage());
        }
    }
}
